import '../Scss/OptionsList.scss'
import { Http } from '../../Api'
import { useState, useEffect, useRef, useCallback } from 'react'
import { useSessionStorageState, useRequest, useBoolean } from 'ahooks'
import { Form, notification, Select, Input, Button, Result, DatePicker, Spin, Popconfirm, message } from 'antd'
import { FormAssembly } from '../../Form/FormAssembly'
import { SceneAnalogData } from '../../Scenes/Mars3d/Data'
import { Initialization } from '../../Scenes/Mars3d/Mars3d'
import dayjs from 'dayjs'

const { mars3d } = window

// 切换项目
export const SwitchProjects = ({ data }) => {
    const { port } = window.location
    const [ProjectList, setProjectList] = useState([])
    useEffect(() => {
        const { project } = data
        const list = Object.keys(project).map(item => ({ label: project[item].title, value: item }))
        setProjectList(list)
    }, [data])

    const NavTo = value => {
        window.location.href = `http://${value}:${port}`
    }

    return (
        <div className="SwitchProjects">
            {ProjectList.map(({ value, label }) => (
                <div key={value} onClick={() => NavTo(value)}>
                    {label}
                </div>
            ))}
        </div>
    )
}

const ApiList = [
    'posLabPenetrationSetOwner',
    'posLabMarshallStabilitySetOwner',
    'posLabDuctilityUpdateRemark',
    'posLabSofteningPointUpdateRemark',
    'posLabDuctilitySetOwner',
    'posLabSofteningPointSetOwner',
    'posLabStressMachineSetOwner',
    'posLabUniversalRebarSetOwner',
    'putLabHumiture',
]

const BccPush = [
    'posBCCenterPushPushLabStressMachine',
    'posBCCenterPushPushLabUniversalRebars',
    'posBCCenterPushPushOrganizationState',
]
// 选择框
export const SelectModal = ({ data, Off }) => {
    const { runAsync } = useRequest(Http, { manual: true })
    const [Value, setValue] = useState()
    const [Options, setOptions] = useState([])
    useEffect(() => {
        const { options } = data.data
        const option = Object.keys(options).map(item => ({ label: options[item], value: item }))
        setOptions(option)
    }, [data])

    const submit = () => {
        const { url, uuid, actionRef } = data.data
        if (ApiList.indexOf(url) !== -1) runAsync({ url, path: [uuid, Value] }).then(() => reload(actionRef))
        if (BccPush.indexOf(url) !== -1) runAsync({ url, path: [Value, uuid, 1] }).then(() => reload(actionRef))
    }
    const reload = e => {
        e.current.reload()
        Off()
    }
    return (
        <div className="SelectModal">
            <div>
                <div>{data.data.label} : </div>
                <Select value={Value} options={Options} onChange={e => setValue(e)} />
            </div>
            <div>
                <Button type="primary" onClick={submit}>
                    保存
                </Button>
            </div>
        </div>
    )
}

// 输入框
export const InputModal = ({ data, Off }) => {
    const { runAsync } = useRequest(Http, { manual: true })
    const { url, label, field, record, actionRef } = data.data
    const [Value, setValue] = useState(record[field])
    const submit = () => {
        if (url === 'posScoreManagementAddProjectScore') {
            const { projectUuid, yearMonth } = record
            runAsync({ url, path: [projectUuid, yearMonth, Value] }).then(successFunc)
        } else if (url === 'posScoreManagementAddWinningBidderScore') {
            const { winningBidderUuid, yearMonth } = record
            runAsync({ url, path: [winningBidderUuid, yearMonth, Value] }).then(successFunc)
        } else runAsync({ url, data: { ...record, [field]: Value }, path: [record.uuid] }).then(successFunc)
    }

    const successFunc = () => {
        actionRef.current.reload()
        Off()
    }

    return (
        <div className="SelectModal">
            <div>
                <div>{label} : </div>
                <Input placeholder={`请输入${label}`} value={Value} onChange={e => setValue(e.target.value)} />
            </div>
            <div>
                <Button type="primary" onClick={submit}>
                    保存{label}
                </Button>
            </div>
        </div>
    )
}

// 多选操作
export const Multiple = ({ data, Off }) => {
    const { MultipleEvent, options } = data
    const [extra, setExtra] = useState([])
    useEffect(() => {
        const data = options.map(({ title, type, emit, danger }, index) => (
            <Button
                key={index}
                type={type}
                size="large"
                danger={danger}
                onClick={() => {
                    if (emit === 'off') {
                        Off()
                    } else MultipleEvent.emit({ emit, Off })
                }}
            >
                {title}
            </Button>
        ))
        setExtra(data)
    }, [options, MultipleEvent, Off])

    return <Result status="warning" title="请谨慎选择一下操作!" extra={extra} />
}

// 修改密码
export const ModifyPassWord = ({ Off }) => {
    const [{ userName, userUuid }] = useSessionStorageState('UserInfo')
    const { runAsync } = useRequest(Http, { manual: true })
    const [Loading, { setTrue, setFalse }] = useBoolean(false)
    return (
        <Form
            layout="horizontal"
            className="ModifyPasswordForm"
            name="basic"
            autoComplete="off"
            onFinish={e => {
                setTrue()
                const { oldPassword, newPassword } = e
                runAsync({
                    url: 'posUserChangePassword',
                    data: { userName, userUuid, oldPassword, newPassword },
                })
                    .then(res => {
                        notification.success({ message: `密码修改成功!`, duration: 2 })
                        Off()
                    })
                    .catch(setFalse)
            }}
        >
            <Form.Item
                name="oldPassword"
                label="原登录密码"
                rules={[{ required: true, message: '必须填写原登录密码!' }]}
            >
                <Input.Password placeholder="请输入登录账户" />
            </Form.Item>

            <Form.Item
                name="newPassword"
                label="设置新密码"
                rules={[{ required: true, message: '必须填写新登录密码' }]}
            >
                <Input.Password placeholder="请输入新的登录密码" />
            </Form.Item>

            <Form.Item
                name="confirm"
                label="重复新密码"
                dependencies={['newPassword']}
                rules={[
                    { required: true, message: '必须验证新密码' },
                    ({ getFieldValue }) => ({
                        validator(_, value) {
                            if (!value || getFieldValue('newPassword') === value) return Promise.resolve()
                            return Promise.reject(new Error('您输入的两个密码不匹配！'))
                        },
                    }),
                ]}
            >
                <Input.Password placeholder="请确认新的登录密码" />
            </Form.Item>

            <Form.Item className="SignUpBtn">
                <Button block type="primary" htmlType="submit" loading={Loading}>
                    {Loading ? '提交中...' : '提交'}
                </Button>
            </Form.Item>
        </Form>
    )
}

// 试验室处理意见
export const LabHandling = ({ data, Off }) => {
    const [Obj, setObj] = useState()
    useEffect(() => {
        const { url, options, groupId, uuid } = data.data
        const { userName: handleUserName } = JSON.parse(sessionStorage.getItem('UserInfo'))
        const obj = {
            added: url,
            modify: url,
            initialValues: { groupId, uuid, handleUserName },
            columns: [
                { dataIndex: 'uuid', valueType: 'hidden' },
                { dataIndex: 'groupId', valueType: 'hidden' },
                { dataIndex: 'handleUserName', valueType: 'hidden' },
                {
                    dataIndex: 'labHandleTypeUuid',
                    title: '处理意见',
                    valueType: 'select',
                    valueEnum: options,
                    rules: true,
                },
                {
                    dataIndex: 'handleTime',
                    title: '审核时间',
                    valueType: 'Date',
                    showTime: true,
                    rules: true,
                },
                {
                    dataIndex: 'remark',
                    title: '意见说明',
                    valueType: 'textarea',
                    rules: true,
                },
            ],
        }
        setObj(obj)
    }, [data])
    if (Obj) return <FormAssembly Off={Off} configure={Obj} actionRef={data.data.actionRef} />
}

// 上传项目评分
export const SynchronizeScore = ({ data, Off }) => {
    const { type, url } = data.data
    const { runAsync } = useRequest(Http, { manual: true })
    const { runAsync: getData } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            setCenterUuid(res[0].uuid)
            setOptions(res.map(({ uuid, centName }) => ({ label: centName, value: uuid })))
        },
    })
    const [Options, setOptions] = useState()
    const [centerUuid, setCenterUuid] = useState()
    const [yearMonth, setYearMonth] = useState(dayjs())
    useEffect(() => {
        getData({ url: 'getDataSynchronizationGetSelects' })
    }, [getData])
    const Submit = () => {
        const path = [centerUuid, type, yearMonth.format('YYYY-MM')]
        runAsync({ url, path }).then(() => Off())
    }
    return (
        <div className="SynchronizeScore">
            <div className="label">
                <div>上传位置 : </div>
                <Select style={{ width: 200 }} value={centerUuid} options={Options} onChange={setCenterUuid} />
            </div>
            <div className="label">
                <div>上传年月 : </div>
                <DatePicker value={yearMonth} onChange={setYearMonth} picker="month" />
            </div>
            <div className="tips">只有“审核通过”以后才可以上传评分，请选择要上传的评分年月！！！</div>
            <div className="submit">
                <Button className="TableBtn" type="primary" onClick={Submit}>
                    上传评分
                </Button>
            </div>
        </div>
    )
}

// 地图定位
export const MapPositionModal = ({ data }) => {
    const { record, url, field } = data.data
    const [messageApi, contextHolder] = message.useMessage()
    const { runAsync: getData } = useRequest(Http, { manual: true })
    const MapBox = useRef()
    const [Position, setPosition] = useState([])
    const [loading, { setTrue, setFalse }] = useBoolean(false)
    const DrawPoint = useCallback(
        ({ map, gra, position }) => {
            gra.clear()
            setPosition(position)
            const company = new mars3d.graphic.BillboardEntity({
                position,
                style: {
                    image: 'https://image.ljkjkf.com/intellisiteSystem_TieKe/Style/Billboard/小三角.png',
                    label: {
                        text: record.tableName,
                        font_size: 18,
                        color: 'red',
                        pixelOffsetY: -40,
                        outline: true,
                        outlineColor: '#f8f8f8',
                        outlineWidth: 2,
                    },
                },
            })
            gra.addGraphic(company)
            map.flyToGraphic(company, { radius: 8000 })
        },
        [record],
    )

    useEffect(() => {
        const { map, gra } = Initialization({ MapBox, Scene: SceneAnalogData, Layer: {} })
        getData({ url: 'getProjectInfoInfo', path: [record.uuid] }).then(res => {
            if (res) DrawPoint({ map, gra, position: res[field] })
        })
        map.on('click', e => {
            map.setCursor(false)
            const cartesian = e.cartesian
            const { lng, lat, alt } = mars3d.LngLatPoint.fromCartesian(cartesian)
            DrawPoint({ map, gra, position: [lng, lat, alt], record })
        })
    }, [DrawPoint, record, getData, field])
    const { runAsync: putData } = useRequest(Http, { manual: true })
    const SaveAddress = () => {
        setTrue()
        let data = { organizationUuid: record.uuid, [field]: Position }
        putData({ url: url, data })
            .then(() => {
                messageApi.success('保存成功')
                setFalse()
            })
            .catch(setFalse)
    }
    return (
        <div className="MapPositionModal">
            {contextHolder}
            <Spin spinning={loading}>
                <div className="MapBox" ref={MapBox}>
                    {Position.length !== 0 && (
                        <div className="SaveAddress">
                            <Popconfirm
                                title="保存后将覆盖已有位置信息"
                                onConfirm={SaveAddress}
                                okText="保存"
                                cancelText="取消"
                            >
                                <Button type="primary">保存位置</Button>
                            </Popconfirm>
                        </div>
                    )}
                </div>
            </Spin>
        </div>
    )
}

// AI预警处理
export const AIPicturesModal = ({ data, Off }) => {
    const [Obj, setObj] = useState()
    useEffect(() => {
        const { url, uuid } = data.data
        setObj({
            modify: url,
            initialValues: { uuid },
            columns: [
                { dataIndex: 'uuid', valueType: 'hidden' },
                {
                    dataIndex: 'handleTime',
                    title: '审核时间',
                    valueType: 'Date',
                    showTime: true,
                    rules: true,
                },
                {
                    dataIndex: 'remark',
                    title: '意见说明',
                    valueType: 'textarea',
                    rules: true,
                },

                {
                    dataIndex: 'attachmentUuid',
                    title: '处理后图片',
                    valueType: 'upload',
                    valueFile: [1],
                    fileUrl: 'fileUrl',
                    hideInSearch: true,
                    hideInTable: true,
                    rules: true,
                },
                {
                    dataIndex: 'fileUrl',
                    title: '处理后图片',
                    valueType: 'hidden',
                    hideInSearch: true,
                    hideInTable: true,
                    width: 400,
                },
            ],
        })
    }, [data])
    if (Obj) return <FormAssembly Off={Off} data={data.data.record} configure={Obj} actionRef={data.data.actionRef} />
}
